#include <pic16/pic18f2550.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "hd44780.h"
#include "four_unsigned_char_to_unsigned_long.h"

#define DEBUG

/**** Global Variables ****/
unsigned char i;
unsigned long long_counter;
unsigned char char_counter[4];
unsigned long long_counters[4];

void main(void) {
	unsigned char len;
	unsigned char lcd_buf[16];
	
	OSCCONbits.SCS = 0x0;		// System Clock Select bits = External oscillator
	OSCCONbits.IRCF = 0x7;		// Internal Oscillator Frequency Select bits 8 MHz (INTOSC drives clock directly)
	
	lcd_init();
	while (1) {
		for (long_counter = 0; long_counter < 0xffff0000; long_counter += 5000) {
			// split long_counter to four unsigned char's
			for (i = 0; i < 4; i++) {
			//	char_counter[i] = (long_counter & (0xff << (i * 8))) >> (i * 8);
				long_counters[i] = (long_counter & (0xff << (i * 8))) >> (i * 8);
			}
			
			// convert them to unsigned int again
		//	long_counter =  (unsigned long)((unsigned long)char_counter[0] | 
		//									(unsigned long)((unsigned long)char_counter[1] << (unsigned long)8) | 
		//									(unsigned long)((unsigned long)char_counter[2] << (unsigned long)16) | 
		//									(unsigned long)((unsigned long)char_counter[3] << (unsigned long)24));
			long_counter = long_counters[0] | (long_counters[1] << 8) | (long_counters[2] << 16) | (long_counters[3] << 24);
			sprintf(lcd_buf, "%lu", long_counter);
			debug(lcd_buf);			
		}
	}
}

void debug(unsigned char *s) {
	unsigned char i;

	lcd_clear();
	for (i = 0; i < 8; i++) {
		if (!s[i]) {
			return;
		}
		send_data(s[i]);
	}

	lcd_ddram(SECOND_LINE);

	for (i = 0; i < 8; i++) {
		if (!s[i + 8]) {
			return;
		}
		send_data(s[i + 8]);
	}
}
